package com.ml.ws.handler;

import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ml.ws.model.PingMessage;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

@Component
public class HeartBeat {
    public static Long timeMessage = 0L;

    @Autowired(required = false)
    ConcurrentHashMap<Channel, Integer> topicMap;

    @Scheduled(fixedDelay = 10000)
    public void pushKline() {
        Long time = System.currentTimeMillis();
        timeMessage = time;
        String message = JSON.toJSONString(new PingMessage(time));
        TextWebSocketFrame frame = new TextWebSocketFrame(message);
        topicMap.forEach((k, v) -> {
            v++;
            if (v > 2) {
                k.writeAndFlush(new CloseWebSocketFrame());
                k.close();
            } else {
                k.writeAndFlush(frame);
                topicMap.put(k,v);
            }

        });
    }
}
